<template>
    <van-page class="my-page" title="我的" :sticky="true">
        <!-- 顶部设置和地址区域 -->
        <div class="top-bar">
            <van-icon name="setting-o" size="24" @click="handleSetting" />
            <div class="location-info" @click="handleAddress">
                <van-icon name="location-o" size="18" />
                <span class="address-text">{{ userAddress || '点击设置地址' }}</span>
                <van-icon name="arrow-right" size="16" />
            </div>
        </div>

        <!-- 用户信息区域 -->
        <div class="user-info">
            <van-image round width="80" height="80"
                :src="userInfo.avatar || 'https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg'" class="avatar" />
            <div class="user-detail">
                <div class="username">{{ userInfo.username || '未设置用户名' }}</div>
                <div class="phone-number" @click="ToLogin">{{ userInfo.phone || '未登录' }}</div>
                <van-button size="small" type="primary" round class="edit-btn">
                    编辑资料
                </van-button>
            </div>
        </div>

        <!-- 订单状态区域 -->
        <div class="order-section">
            <div class="order-title">
                <span>我的订单</span>
                <van-button size="mini" type="text" class="more-btn">
                    全部订单 <van-icon name="arrow-right" size="14" />
                </van-button>
            </div>

            <van-grid :column-num="4" border="false" class="order-grid">
                <van-grid-item icon="gold-coin-o" text="待付款" @click="handleOrder('pay')" />
                <span class="order-count">{{ orderStats.unpaid || 0 }}</span>
                <van-grid-item icon="todo-list-o" text="待发货" @click="handleOrder('ship')" />
                <span class="order-count">{{ orderStats.unshipped || 0 }}</span>
                <van-grid-item icon="more-o" text="待收货" @click="handleOrder('receive')" />
                <span class="order-count">{{ orderStats.unreceived || 0 }}</span>
                <van-grid-item icon="comment-o" text="待评价" @click="handleOrder('comment')" />
                <span class="order-count">{{ orderStats.uncommented || 0 }}</span>
            </van-grid>
        </div>

        <!-- 功能区域 -->
        <van-grid :column-num="3" class="function-grid">
            <van-grid-item icon="coupon-o" text="优惠券" @click="handleCoupon" />
            <van-grid-item icon="balance-o" text="我的钱包" @click="handleWallet" />
            <van-grid-item icon="star-o" text="我的收藏" @click="handleCollect" />
            <van-grid-item icon="gift-o" text="我的礼品卡" @click="handleGiftCard" />
            <van-grid-item icon="service-o" text="售后服务" @click="handleAfterSale" />
            <van-grid-item icon="service-o" text="我的足迹" @click="handleFootprint" />
        </van-grid>

        <!-- 底部其他功能区 -->
        <div class="other-section">
            <van-cell-group inset>
                <van-cell title="我的等级" is-link @click="handleVip" :value="vipLevel" />
                <van-cell title="我的积分" is-link @click="handlePoints" :value="userPoints + ' 积分'" />
                <van-cell title="设置" is-link @click="handleSetting" />
            </van-cell-group>
        </div>

        <!-- 退出登录按钮 -->
        <div class="logout-container">
            <van-button type="danger" block @click="handleLogout">退出登录</van-button>
        </div>
    </van-page>
    <Button></Button>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import api from '@/api/history.js'
import { showFailToast, showConfirmDialog, showSuccessToast } from 'vant';
import Button from '@/components/Button.vue';
import { useRouter } from 'vue-router';

const router = useRouter();
// 存储用户信息（从接口获取）
const userInfo = ref({
    avatar: '', // 用户头像
    phone: '',  // 手机号
    username: '' // 昵称（预留）
});
const userAddress = ref(''); // 用户默认地址
const orderStats = ref({
    unpaid: 0,      // 待付款数量
    unshipped: 0,   // 待发货数量
    unreceived: 0,  // 待收货数量
    uncommented: 0  // 待评价数量
});
const couponCount = ref(0); // 优惠券数量
const userPoints = ref(0);  // 用户积分
const vipLevel = ref(''); // 会员等级

// 跳转登录页面
const ToLogin = () => {
    router.push('/login');
}

// 页面加载时获取用户信息（核心接口：获取个人中心数据）
onMounted(() => {
    fetchUserInfo(); // 获取用户基本信息
    // fetchOrderStats(); // 获取订单状态统计
    // fetchCouponCount(); // 获取优惠券数量
    // fetchUserPoints(); // 获取用户积分
});

// 1. 获取用户基本信息接口
const fetchUserInfo = async () => {
    try {
        const token = localStorage.getItem('token');
        console.log('token', token);
        if (!token) {

            userInfo.value = { avatar: '', phone: '', username:'' };
            userAddress.value = '';
            return;
        }


        // 统一使用 http 实例（确保拦截器已配置）
        const res = await api.get('/user/user_info');

        console.log('res', res);
        if (res.data && res.data.username) {
            userInfo.value = {
                avatar: res.data.avatar || '',
                phone: res.data.phone || '',
                username: res.data.username
            };
            if (userInfo.value.phone && userInfo.value.phone.length === 11) {
                userInfo.value.phone = userInfo.value.phone.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3');
            }
            userAddress.value = res.data.defaultAddress || '';
        } else {
            userInfo.value = { avatar: '', phone: '登录异常', username:'' };
            VanToast.fail('用户信息格式错误');
        }
    } catch (err) {
        console.error('用户信息接口请求失败：', err);
        
        if (err.response && err.response.status === 401) {
            // 处理 token 无效/过期的情况
            localStorage.removeItem('token');
            userInfo.value = { avatar: '', phone: '未登录', username: '' };
            userAddress.value = '';
            VanToast.fail('登录已过期，请重新登录');
            // 自动跳转到登录页
            router.push('/login');
        } else {
            userInfo.value = { avatar: '', phone: '获取失败', username: '' };
            userAddress.value = '';
            showFailToast('网络错误，请重试');
        }
    }
};

// 2. 获取订单状态统计接口
// const fetchOrderStats = async () => {
//     try {
//         // 后端接口示例：获取各状态订单数量
//         const res = await api.get('/api/order/stats');
//         /* 
//           接口返回示例：
//           {
//             code: 200,
//             data: {
//               unpaid: 1,
//               unshipped: 2,
//               unreceived: 3,
//               uncommented: 0
//             }
//           }
//         */
//         if (res.data.code === 200) {
//             orderStats.value = res.data.data;
//         } else {
//             showFailToast('获取订单数据失败');
//         }
//     } catch (err) {
//         console.error('订单统计接口请求失败：', err);
//     }
// };

// 3. 获取优惠券数量接口
// const fetchCouponCount = async () => {
//     try {
//         // 后端接口示例：获取可用优惠券数量
//         const res = await api.get('/api/coupon/count');
//         /* 
//           接口返回示例：
//           {
//             code: 200,
//             data: 5 // 可用优惠券数量
//           }
//         */
//         if (res.data.code === 200) {
//             couponCount.value = res.data.data;
//         }
//     } catch (err) {
//         console.error('优惠券接口请求失败：', err);
//     }
// };

// 4. 获取用户积分接口
// const fetchUserPoints = async () => {
//     try {
//         // 后端接口示例：获取用户积分
//         const res = await api.get('/api/user/points');
//         /* 
//           接口返回示例：
//           {
//             code: 200,
//             data: 1250 // 积分数量
//           }
//         */
//         if (res.data.code === 200) {
//             userPoints.value = res.data.data;
//         }
//     } catch (err) {
//         console.error('积分接口请求失败：', err);
//     }
// };

// 5. 退出登录接口
const handleLogout = async () => {
  try {
    const confirm = await showConfirmDialog({
      title: '退出登录',
      message: '确定要退出当前账号吗？',
    });
    if (confirm) {
      const res = await api.post('/user/logout');
      console.log("退出登录",res)
      if (res.status === 200) {
        showSuccessToast('退出成功');
        localStorage.removeItem('token');
        router.push('/login');
      } else {
        showFailToast(res.data.message || '退出失败');
      }
    }
  } catch (err) {
    console.error('退出登录失败：', err);
    if (err !== 'cancel') { // 排除用户取消操作的情况
      showFailToast('网络错误，请重试');
    }
  }
}
// 其他功能按钮点击事件（预留接口调用位置）
const handleAddress = () => {
    // 跳转地址管理页，可调用接口：/api/address/list 获取地址列表
    router.push('/location');
};

const handleOrder = (type) => {
    // 跳转对应状态的订单列表，可调用接口：/api/order/list?status=xxx
    console.log(`打开${type}订单列表，接口参数：status=${type}`);
};

const handleVip = () => {
    // 跳转会员中心，可调用接口：/api/vip/info 获取会员信息
    console.log('打开我的等级'); 
    router.push('/Member')
};

const handleCoupon = () => {
    // 跳转优惠券列表，可调用接口：/api/coupon/list 获取优惠券列表
    console.log('打开优惠券列表，可调用优惠券接口');
};

// 其他功能的点击事件（均预留接口调用位置）
const handleSetting = () => console.log('打开设置页，可调用设置相关接口');
const handleWallet = () => console.log('打开钱包页，可调用钱包接口：/api/wallet/info');
const handleCollect = () => console.log('打开收藏页，可调用收藏列表接口：/api/collect/list');
const handleBankCard = () => console.log('打开银行卡页，可调用银行卡接口：/api/bankcard/list');
const handleGiftCard = () => console.log('打开礼品卡页，可调用礼品卡接口：/api/giftcard/list');
const handleService = () => console.log('打开客服页，可调用客服相关接口');
const handleAfterSale = () => console.log('打开售后页，可调用售后列表接口：/api/aftersale/list');
const handleFootprint = () => {
    router.push('/history');
};
const handlePoints = () => console.log('打开积分页，可调用积分明细接口：/api/points/detail');
</script>

<style scoped>
/* 样式与之前保持一致，此处省略 */
.my-page {
    background-color: #f5f5f5;
    --van-page-content-padding: 16px;
}

.top-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    margin-bottom: 15px;
}

.location-info {
    display: flex;
    align-items: center;
    color: #333;
}

.address-text {
    margin: 0 6px;
    font-size: 15px;
    max-width: 200px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.user-info {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px 16px;
    display: flex;
    align-items: center;
    margin-bottom: 15px;
}

.user-detail .username {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin-bottom: 4px;
}

.user-detail .phone-number {
    font-size: 14px;
    color: #666;
}

.avatar {
    border: 2px solid #f0f0f0;
}

.user-detail {
    margin-left: 16px;
    flex: 1;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.phone-number {
    font-size: 18px;
    font-weight: 500;
    color: #333;
}

.edit-btn {
    background-color: #ff6b00;
}

.order-section {
    background-color: #fff;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 15px;
}

.order-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.order-title span {
    font-size: 16px;
    font-weight: 500;
    color: #333;
}

.more-btn {
    color: #f0f0f0;
    padding: 0;
    font-size: 14px;
}

.order-grid {
    --van-grid-item-content-padding: 10px 0;
}

.order-count {
    position: absolute;
    top: 5px;
    right: 25px;
    background-color: #e62828;
    color: #fff;
    font-size: 12px;
    width: 16px;
    height: 16px;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.function-grid {
    background-color: #fff;
    border-radius: 8px;
    padding-top: 10px;
    margin-bottom: 15px;
}

.van-grid-item__content {
    flex-direction: column;
    padding: 15px 0;
}

.van-grid-item__icon {
    font-size: 24px;
    color: #666;
    margin-bottom: 8px;
}

.van-grid-item__text {
    font-size: 14px;
    color: #333;
}

.other-section {
    margin-bottom: 20px;
}

.logout-container {
    padding: 0 16px;
}
</style>